<template>
  <div>
    <van-button :type="type"
                :size="size"
                @getphonenumber="getPhoneNumber"
                open-type="getPhoneNumber">{{title}}</van-button>
  </div>
</template>
<script>
export default {
  props: {
    title: {
      type: String,
      default: '获取电话号码'
    },
    type: {
      type: String,
      default: 'primary'
    },
    size: {
      type: String,
      default: 'normal'
    }
  },
  methods: {
    getPhoneNumber (e) {
      let that = this
      console.log('获取电话号码的加密数据：', e)
      wx.login({
        success: function (res) {
          console.log(res)
          if (!e.mp.detail.errMsg || e.mp.detail.errMsg !== 'getPhoneNumber:ok') {
            console.log('获取失败')
            return false
          }
          if (!e.mp.detail.cloudID) {
            console.log('未获取到cloudID，请检查微信开发者工具版本')
          }
          wx.cloud.callFunction({
            name: 'init',
            data: {
              phoneNumber: wx.cloud.CloudID(e.mp.detail.cloudID)
            },
            success: function (result) {
              // 获取电话号码成功后，保存到状态数据，并更新数据库
              console.log(result)
              let phoneNumber = result.result.event.phoneNumber.data.phoneNumber
              that.$store.commit('updatePhoneNumber', phoneNumber)
              that.updateUserPhoneNumber(phoneNumber)
            },
            fail: function (result) {
              console.log(result)
            }
          })
        }
      })
    },
    updateUserPhoneNumber (phoneNumber) {
      let that = this
      var db = wx.cloud.database()
      var userInfo = db.collection('app_users')
      userInfo.doc(that.$store.state.userId).update({
        data: {
          phoneNumber: phoneNumber
        },
        success: function (res) {
          console.log(res)
        },
        fail: function (res) {
          console.log(res)
        }
      })
    }
  }
}
</script>
<style scoped>
</style>